#!usr/bin/env python
# -*- coding:utf-8 -*-
# user nanme: Mr.zhang
# data time : 2022/9/16   6:31 下午
# project   : conftest.py
# IDE       : PyCharm
# email     :17600960626@163.com

import platform
import time
import paramiko
from filelock import FileLock
import drivers.android
import os
import requests
import pytest
from lib.loggers import log
import allure

'''
全局配置，与case配合使用，每次case运行，返回首页即可运行下一个模块
需要第一条case运行完成后返回到主页
注：此文件不要随意更改，共享文件
'''



def pytest_collection_modifyitems(items):
    for item in items:
        item.name = item.name.encode("utf-8").decode("unicode_escape")
        item._nodeid = item.nodeid.encode("utf-8").decode("unicode_escape")


def _capture_screenshot(nodeid):
    '''截图保存为base64'''
    scrname = nodeid[nodeid.index('[')+1:nodeid.index(']')]
    global driver
    driver.screenshot('report/' + scrname + '.png')
    return scrname + '.png'

# @pytest.hookimpl(tryfirst=True,hookwrapper=True)
# def pytest_runtest_makereport(itme,call):
#     out = yield
#     rep = out.get_result()
#     if rep.when == 'call' and rep.failed:
#         allure.attach(driver.get_screenshot_as_pag(),'失败截图',allure.attachment_type.PNG)




#初始化设备
@pytest.fixture(scope="session", autouse=True)
def driver(tmp_path_factory):
    devices_list = drivers.android.devices()
    if not devices_list:
        raise

    global device

    # if worker_id == "master":
    #     log.info('单台测试')
    #     device = drivers.android.device_android(devices_list[0])
    #     return device

    root_tmp_dir = tmp_path_factory.getbasetemp().parent
    fn = root_tmp_dir / "devices.json"
    # log.info(type(fn))
    # log.info(fn)
    # log.info(fn.is_file())
    # log.info('fn.is_file()')
    with FileLock(str(fn) + ".lock"):
        # log.info(fn.is_file())
        if fn.is_file():
            devices_ls = fn.read_text()
            if not devices_ls:
                return Exception('No Device')
            device_serial, devices_l = _devices_list_pop(devices_ls)
            device = drivers.android.device_android(device_serial)
            fn.write_text(
                str(devices_l)
            )
        else:
            device = drivers.android.device_android(devices_list[0])
            devices_list.pop(0)
            fn.write_text(str(devices_list))
    # log.info(device)
    return device


def _devices_list_pop(dl):
    d = dl[1:-1].replace("'", '').strip().split(', ')
    ds = d[0]
    d.pop(0)
    return ds, d




class Failed:
    # 跳过用例
    skip = False
